<template>
    <div class="app-container">
        <el-dialog :title="title" :visible.sync="visible" width="600px" v-if="visible" append-to-body
            :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" :label-width="labelWidth" v-loading="bodyLoading">
                <el-form-item label="选择分红日期" prop="bonusTime" ref="">
                    <el-date-picker v-model="form.bonusTime" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
                        placeholder="选择日期" :picker-options="expireTimeOPtion" :style="{ width: inputWidth }">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="分红类型" prop="bonusType">
                    <el-select filterable v-model="form.bonusType" placeholder="请选择" clearable
                        :style="{ width: inputWidth }">
                        <el-option v-for="dict in options" :key="dict.id" :label="dict.value" :value="dict.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="分红数额" prop="bonusMoney">
                    <el-input type="text" v-model="form.bonusMoney" placeholder="请输入"
                        :style="{ width: inputWidth }"></el-input>
                </el-form-item>
                <el-form-item label="分红人数" prop="customerAmount" v-if="form.limitCustomerAmount == 1">
                    <el-input type="text" v-model="form.customerAmount" placeholder="请输入"
                        :style="{ width: inputWidth }"></el-input>
                </el-form-item>
                <el-form-item label="" prop="limitCustomerAmount">
                    <el-checkbox v-model="form.limitCustomerAmount" :true-label="'2'" :false-label="'1'">不限人数</el-checkbox>
                </el-form-item>
                <p class="formula">分红系数=分红金额/总参与分红用户的CoCo总持有值（保留小数点后4位）<br/>用户获得分红金额=当前用户持有CoCo * 分红系数(低于0.01不可获得分红)</p>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm" :loading="submitLoading">保存</el-button>
                <el-button @click="cancel">取消</el-button>
                <!-- <el-button @click="imitateView" v-if="form.id!=''">分红模拟</el-button> -->
            </div>
        </el-dialog>
        <!-- 模拟结果 -->
        <!-- <imitate-dialog ref="imitateDialogRef"></imitate-dialog> -->
    </div>
</template>
  
<script>
import {
    addBonus, bonusDetail, editBonus
} from "@/api/integralOperation/CoCoBonus";
import imitateDialog from "../components/imitateDialog.vue"
export default {
    // dicts: ['asset_card_type'],
    name: "Dialog",
    components: {
        imitateDialog,
    },
    data() {
        var checkBonusMoney = (rule, value, callback) => {
            var reg = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/
            if (value === '') {
                callback(new Error('请输入分红数额'));
            } else if (!reg.test(value) || value == '0.00' || value == '0.0') {
                callback(new Error('请输入大于0的数值，最多保留两位小数'));
            } else {
                callback()
            }
        };
        var checkCustomerAmount = (rule, value, callback) => {
            var reg = /(^[1-9]\d*$)/
            if (value === '') {
                callback(new Error('请输入分红人数'));
            } else if (!reg.test(value)) {
                callback(new Error('请输入大于0的正整数'));
            } else {
                callback()
            }
        };
        return {
            expireTimeOPtion: { //限制选择今日及往后的日期
                disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7;  //如果没有后面的-8.64e7就是不可以选择今天的 
                }
            },
            bodyLoading: false,
            labelWidth: '120px',
            inputWidth: '400px',
            id: '', //
            submitLoading: false,
            // 是否禁用表单
            disabled: false,
            // 弹出层标题
            title: "添加分红日期",
            // 是否显示弹出层
            visible: false,
            //分红类型
            options: [],
            // 表单参数
            form: {
                bonusMoney: '', //分红金额
                bonusTime: '', //分红日期（yyyy-MM-dd）
                bonusType: '',//分红类型 1 椰分 shenye_coco_bonus_type
                customerAmount: '',//分红人数
                id: '',//CoCo分红id
                limitCustomerAmount: '1',//限制分红人数 1 限制 2 不限制
            },
            // 表单校验
            rules: {
                bonusTime: [{
                    required: true,
                    message: "请选择分红日期",
                    trigger: ["blur", "change"]
                }],
                bonusType: [{
                    required: true,
                    message: "请选择分红类型",
                    trigger: ["blur", "change"]
                }],
                bonusMoney: [{
                    required: true,
                    validator: checkBonusMoney,
                    trigger: ['blur', 'change']
                }],
                customerAmount: [{
                    required: true,
                    validator: checkCustomerAmount,
                    trigger: ['blur', 'change']
                }],
            },
        };
    },
    created() {

    },
    methods: {
        /** 打开发行管理弹框 */
        open(id) {
            console.log(id)
            this.getDict()
            if (id != undefined) {
                this.form.id = id
                this.getBonusDetail(id)
            } else {
                this.form = {
                    bonusMoney: '', //分红金额
                    bonusTime: '', //分红日期（yyyy-MM-dd）
                    bonusType: '',//分红类型 1 椰分 shenye_coco_bonus_type
                    customerAmount: '',//分红人数
                    id: '',//CoCo分红id
                    limitCustomerAmount: '1',//限制分红人数 1 限制 2 不限制
                }
            }
            this.visible = true
        },
        // 取消按钮
        cancel() {
            this.visible = false;
            this.reset();
        },
        // 表单重置
        reset() {
        },
        //获取分红状态字典
        getDict() {
            var dictType = "shenye_coco_bonus_type";
            this.$getSelectList(dictType)
                .then((res) => {
                    this.options = res.result[0].dictList;
                })
                .finally(() => { });
        },
        //获取分红详情
        getBonusDetail(id) {
            this.bodyLoading = true
            bonusDetail(id).then(res => {
                console.log(res)
                this.form = res.result
                this.bodyLoading = false
            }).catch(() => {
                this.bodyLoading = false
            })
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if(this.form.limitCustomerAmount==2){
                        this.form.customerAmount = ''
                    }
                    let data = {
                        ...this.form
                    }
                    this.submitLoading = true
                    console.log(this.form.id)
                    if (this.form.id != '') {
                        editBonus(data).then(response => {
                            this.$message.success('保存成功');
                            setTimeout(() => {
                                this.$emit('refresh')
                                this.cancel()
                                this.submitLoading = false
                            }, 500)
                        }).catch(() => {
                            this.submitLoading = false
                        })
                    } else {
                        addBonus(data).then(response => {
                            this.$message.success('新增成功');
                            setTimeout(() => {
                                this.$emit('refresh')
                                this.cancel()
                                this.submitLoading = false
                            }, 500)

                        }).catch(() => {
                            this.submitLoading = false
                        })
                    }
                }
            });
        },
        // 分红模拟
        imitateView() {
            this.$refs.imitateDialogRef.open(this.form.id);
        },
    }
};

</script>
<style scoped>
.img_box {
    width: 100px;
    height: 70px;
    border-radius: 4px;
}

.flex {
    display: flex;
}

.formula {
    color: #eb1111;
    padding: 0 30px;
    line-height: 24px;
}
</style>
  